﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using NCfg = NHibernate.Cfg;

namespace YasharEl.Infrastructure.ProcessEngine.PersistenceModel.NHibernate.Tests
{
    public class InMemoryDatabaseTest : IDisposable
    {
        private static NCfg.Configuration Configuration;
        private static ISessionFactory SessionFactory;
        protected ISession session;

        public InMemoryDatabaseTest(Assembly[] assemblies)
        {
            if (Configuration == null)
            {
                FluentConfiguration fc = Fluently.Configure()
                    .Database(SQLiteConfiguration.Standard.InMemory());

                foreach (Assembly assembly in assemblies)
                {
                    fc = fc.Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
                }

                fc.ExposeConfiguration(c => Configuration = c);

                SessionFactory = fc.BuildSessionFactory();
            }
            session = SessionFactory.OpenSession();
            new SchemaExport(Configuration).Execute(true, true, false, session.Connection, Console.Out);
        }

        public void Dispose()
        {
            session.Dispose();
        }
    }
}
